package com.hnqcgc.db;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.SQLException;


public class MyTransaction {
    private Connection connection;

    public MyTransaction(boolean isAutoCommit) {
        try {
            //使用C3p0链接数据库
            this.connection = new ComboPooledDataSource().getConnection();
            //设置事务
            //true:自动提交事务
            //false:手动提交事务
            this.connection.setAutoCommit(isAutoCommit);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取设置了事务的数据库连接
     *
     * @return
     */
    public Connection getConn() {
        return connection;
    }

    /**
     * 关闭数据库
     */
    public void closeConn() {
        try {
            if (connection != null && !connection.isClosed()) {
                connection.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public void commit() {
        try {
            connection.commit();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public void rollback() {
        try {
            connection.rollback();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
